#include "asr_stream.h"
#include "asr_stream_test.h"
#include "port_audio.h"
#include "llm_server.h"

#include "conf.h"

#include <memory>
#include <signal.h>
#include <unistd.h>
#include <string>

namespace {
    std::unique_ptr<AsrStream>  asr;
    std::unique_ptr<LlmServer> lserver;

    void llm_server_callback(const std::string & content)
    {
        sys_log("set dataset input finished : true");
        // tts->notifyInputFinished();

        sys_log("gpt response: %s", content.c_str());

        asr->resume();
    }

    void llm_server_stream_callback(const std::string & content)
    {
        // sys_log("send llm server str(%s) to tts.", content.c_str());
        // tts->appendText(content);
    }

    AsrStream::asrContinueEnum asr_callback(std::string &res)
    {
        // sys_log("%s", res.c_str());
        if (res.empty()) {
            return AsrStream::asrContinue; 
        }

        sys_log("asr pause ...... ");
        asr->pause();

        sys_log("send question(%s) to gpt server.", res.c_str());

        lserver->post_request(res);

        return AsrStream::asrContinue;
    }

    void signalHandler(int signum) 
    {
        sys_log("signal handler .... exit ......");
        if (asr)    asr->stop();
        asr.reset();
        exit(signum);  // 释放资源
    }
}

int main(void)
{
    signal(SIGINT, signalHandler);

    // 初始化全局的 portAudio 库
    std::unique_ptr<PortAudioManager> pam = std::make_unique<PortAudioManager>();

    // 初始化访问网络大模型
    lserver = std::make_unique<LlmServer>();
    lserver->setUserCallback(llm_server_callback);
    lserver->setUserStreamCallback(llm_server_stream_callback);

    // 初始化语音识别类
    AsrPunctuation punc("/opt/sherpa-onnx/sherpa-onnx-punct-model/model.onnx");
    asr = std::make_unique<AsrStream>(
        "/opt/sherpa-onnx/sherpa-onnx-streaming-zipformer-zh/encoder-epoch-99-avg-1.onnx",
        "/opt/sherpa-onnx/sherpa-onnx-streaming-zipformer-zh/decoder-epoch-99-avg-1.onnx",
        "/opt/sherpa-onnx/sherpa-onnx-streaming-zipformer-zh/joiner-epoch-99-avg-1.onnx",
        "/opt/sherpa-onnx/sherpa-onnx-streaming-zipformer-zh/tokens.txt",
        "",
        &punc
    );
    asr->setAsrCallback(asr_callback);
    asr->resume();




    // 10 minute asr input test.
    sleep(60 * 10);

    exit(0);
}
